//-------------------- 右键菜单演示 ------------------------//

chrome.contextMenus.create({
	title: '快速查询否词：%s', // %s表示选中的文字
	contexts: ['selection'], // 只有当选中文字时才会出现此右键菜单
	onclick: function(params)
	{
		// 注意不能使用location.href，因为location是属于background的window对象
		openPcSearch(params.selectionText);
		openMobileearch(params.selectionText);
	}
});


/**
 * PC搜索引擎
 * @param  {[type]} keyword [description]
 * @return {[type]}         [description]
 */
function openPcSearch(keyword){
	chrome.tabs.create({url: 'https://www.baidu.com/s?ie=utf-8&wd=' + encodeURI(keyword)});
	chrome.tabs.create({url: 'https://www.so.com/s?ie=utf-8&q=' + encodeURI(keyword)});
	chrome.tabs.create({url: 'https://www.sogou.com/web?query=' + encodeURI(keyword)});
}

function openMobileearch(keyword) {
	chrome.tabs.create({url: 'https://m.sm.cn/s?q=' + encodeURI(keyword)});
	chrome.tabs.create({url: 'https://m.baidu.com/s?word=' + encodeURI(keyword)});
	chrome.tabs.create({url: 'https://m.sogou.com/web/searchList.jsp?keyword=' + encodeURI(keyword)});
	chrome.tabs.create({url: 'https://m.so.com/s?q=' + encodeURI(keyword)});
}

// omnibox 搜索框
chrome.omnibox.onInputEntered.addListener(text => {
	console.log('inputChanged: ' + text);
	if(!text) return;
	openPcSearch(text);
	openMobileearch(text);
});

var iponeUa = "User-Agent:Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5";
chrome.webRequest.onBeforeSendHeaders.addListener(
        function(details) {
          for (var i = 0; i < details.requestHeaders.length; ++i) {
            if (details.requestHeaders[i].name === 'User-Agent') {
              console.log(details.requestHeaders[i]);	
              details.requestHeaders[i].value = iponeUa;
              // details.requestHeaders.splice(i, 1);
              break;
            }
          }
          return {requestHeaders: details.requestHeaders};
        },
        {urls: ["*://m.sm.cn/*","*://m.baidu.com/*","*://m.sogou.com/*","*://m.so.com/*"]},
        ["blocking", "requestHeaders"]);

